package com.health.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.health.dao.OrderSettingMapper;
import com.health.pojo.OrderSetting;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderSettingServiceImpl implements OrderSettingService{

    @Resource
    private OrderSettingMapper orderSettingMapper;

    /**
     * 添加excel表中每行预约设置
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(List<OrderSetting> orderSettingList) {
        for (OrderSetting orderSetting:orderSettingList) {
            handleOrderSetting(orderSetting);
        }
    }
    /**
     * 预约设置查询
     */
    public List<Map<String, Integer>> findByDate(Date date) {
        return orderSettingMapper.findByDate(date);
    }

    /**
     * 预约人数设置
     */
    @Transactional(rollbackFor = Exception.class)
    public void editNumber(OrderSetting orderSetting) {

      handleOrderSetting(orderSetting);
    }

    /**
     * 校验预约日期
     */
    public OrderSetting checkOrderDate(Date orderDate) {

        return orderSettingMapper.findByOrderDate(orderDate);
    }

    /**
     * 预约设置的逻辑业务处理
     */
    private void handleOrderSetting(OrderSetting orderSetting) {
        //根据预约日期查询数据库
        OrderSetting orderSettingDb=orderSettingMapper.findByOrderDate(orderSetting.getOrderDate());

        //判断查询到的预约设置是否为空,是则添加新的预约设置,否则继续判断设置是否合理
        if (orderSettingDb !=null){
            //判断数据库查到的reservations是否比设置的number大,大则无法设置,抛出异常
            if (orderSetting.getNumber()<orderSettingDb.getReservations()){
                //抛出异常
                String orderDate=new SimpleDateFormat("yyyy-MM-dd")
                        .format(orderSetting.getOrderDate());
                throw new RuntimeException("设置最大预约人数小于已预约人数,无法修改设置,设置日期:"
                        +orderDate+"已预约人数:"+orderSettingDb.getReservations());
            }else if (orderSetting.getNumber()>orderSettingDb.getNumber()){//预约设置大于数据库的预约设置时,修改,相等则不动
                orderSettingMapper.updateOrderSettingNumber(orderSetting);
            }

        }else {
            orderSettingMapper.add(orderSetting);
        }

    }
}
